const express = require('express');
const cors = require('cors');
const http = require('http');
const socketIo = require('socket.io');
const sequelize = require('./config/database');
const User = require('./models/User');
const Danmaku = require('./models/Danmaku');
const multer = require('multer');
const xlsx = require('xlsx');
const path = require('path');
const fs = require('fs');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"],
    allowedHeaders: ["Content-Type", "Authorization"],
    credentials: true
  },
  transports: ['websocket', 'polling'],
  pingTimeout: 60000,
  pingInterval: 25000
});

// 配置静态文件目录
app.use(express.static(path.join(__dirname, '../../frontend/dist')));
app.use('/static', express.static(path.join(__dirname, '../static')));

// 确保上传目录和静态资源目录存在
const createUploadDirs = () => {
  const dirs = [
    'uploads', 
    'uploads/excel',
    path.join(__dirname, '../static'),
    path.join(__dirname, '../static/images'),
    path.join(__dirname, '../static/prizes')  // 添加奖品图片目录
  ];
  dirs.forEach(dir => {
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
  });
};
createUploadDirs();

// 配置Excel文件上传
const excelStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/excel');
  },
  filename: function (req, file, cb) {
    cb(null, 'excel-' + Date.now() + path.extname(file.originalname));
  }
});

const excelUpload = multer({
  storage: excelStorage,
  fileFilter: function (req, file, cb) {
    if (!file.originalname.match(/\.(xlsx|xls)$/)) {
      return cb(new Error('只允许上传Excel文件！'), false);
    }
    cb(null, true);
  }
});

// 配置背景图片上传
const imageStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../static/images'));
  },
  filename: function (req, file, cb) {
    cb(null, 'background' + path.extname(file.originalname));
  }
});

// 配置奖品图片上传
const prizeImageStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../static/prizes'));
  },
  filename: function (req, file, cb) {
    // 使用时间戳和原始文件扩展名生成唯一文件名
    cb(null, 'prize-' + Date.now() + path.extname(file.originalname));
  }
});

const imageUpload = multer({
  storage: imageStorage,
  fileFilter: function (req, file, cb) {
    if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/i)) {
      return cb(new Error('只允许上传图片文件！'), false);
    }
    cb(null, true);
  }
});

const prizeImageUpload = multer({
  storage: prizeImageStorage,
  fileFilter: function (req, file, cb) {
    if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/i)) {
      return cb(new Error('只允许上传图片文件！'), false);
    }
    cb(null, true);
  }
});

app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
}));
app.use(express.json());

// 数据库同步
sequelize.sync().then(() => {
  console.log('数据库已同步');
});

// 下载Excel模板
app.get('/api/template/download', (req, res) => {
  try {
    // 创建工作簿和工作表
    const workbook = xlsx.utils.book_new();
    
    // 示例数据
    const templateData = [
      {
        姓名: '张三',
        部门: '技术部',
        工号: '001',
        手机号: '13800138000'
      },
      {
        姓名: '李四',
        部门: '市场部',
        工号: '002',
        手机号: '13800138001'
      }
    ];
    
    // 创建工作表
    const worksheet = xlsx.utils.json_to_sheet(templateData);
    
    // 设置列宽
    const colWidths = [
      { wch: 15 }, // 姓名
      { wch: 20 }, // 部门
      { wch: 15 }, // 工号
      { wch: 15 }  // 手机号
    ];
    worksheet['!cols'] = colWidths;
    
    // 将工作表添加到工作簿
    xlsx.utils.book_append_sheet(workbook, worksheet, '抽奖名单模板');
    
    // 生成临时文件路径
    const tempFilePath = path.join('uploads', 'lottery_template.xlsx');
    
    // 写入文件
    xlsx.writeFile(workbook, tempFilePath);
    
    // 发送文件
    res.download(tempFilePath, '抽奖名单模板.xlsx', (err) => {
      // 下载完成后删除临时文件
      if (fs.existsSync(tempFilePath)) {
        fs.unlinkSync(tempFilePath);
      }
    });
  } catch (error) {
    console.error('生成模板失败:', error);
    res.status(500).json({ error: '生成模板失败' });
  }
});

// Excel导入用户
app.post('/api/users/import', excelUpload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: '请上传文件' });
    }

    const workbook = xlsx.readFile(req.file.path);
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];
    const data = xlsx.utils.sheet_to_json(worksheet);

    // 清除现有用户
    await User.destroy({ where: {} });

    // 导入新用户
    const users = await User.bulkCreate(
      data.map(row => ({
        name: row.name || row['姓名'],
        department: row.department || row['部门'] || null,
        employeeId: row['工号'] || null,
        phone: row['手机号'] || null
      }))
    );

    // 删除上传的文件
    fs.unlinkSync(req.file.path);

    res.json({ message: '导入成功', count: users.length });
  } catch (error) {
    console.error('导入失败:', error);
    if (req.file && fs.existsSync(req.file.path)) {
      fs.unlinkSync(req.file.path);
    }
    res.status(500).json({ error: '导入失败: ' + error.message });
  }
});

// 添加获取最近弹幕的接口
app.get('/api/danmaku/recent', async (req, res) => {
  try {
    const recentDanmakus = await Danmaku.findAll({
      order: [['createdAt', 'DESC']],
      limit: 30
    });
    res.json(recentDanmakus.reverse());  // 返回最近30条弹幕，按时间正序排列
  } catch (error) {
    console.error('获取最近弹幕失败:', error);
    res.status(500).json({ error: '获取最近弹幕失败' });
  }
});

// Socket.IO 连接处理
io.on('connection', (socket) => {
  console.log('新的客户端连接');

  // 监听新弹幕
  socket.on('new-danmaku', async (data) => {
    try {
      const danmaku = await Danmaku.create({
        content: data.content,
        color: data.color || '#ffffff',
        createdAt: new Date()
      });
      
      // 广播新弹幕给所有客户端
      io.emit('danmaku', danmaku);
      
      console.log('新弹幕已创建并广播:', danmaku);
    } catch (error) {
      console.error('创建弹幕失败:', error);
      socket.emit('error', { message: '创建弹幕失败' });
    }
  });

  // 监听抽奖开始
  socket.on('start-lottery', async () => {
    try {
      const users = await User.findAll({
        where: { isWinner: false }
      });
      io.emit('lottery-pool', users);
    } catch (error) {
      console.error('获取抽奖池失败:', error);
    }
  });

  socket.on('disconnect', () => {
    console.log('客户端断开连接');
  });
});

// API 路由
app.get('/api/users', async (req, res) => {
  try {
    const users = await User.findAll();
    res.json(users);
  } catch (error) {
    res.status(500).json({ error: '获取用户列表失败' });
  }
});

app.get('/api/danmaku/recent', async (req, res) => {
  try {
    const danmakus = await Danmaku.findAll({
      order: [['timestamp', 'DESC']],
      limit: 30
    });
    res.json(danmakus);
  } catch (error) {
    res.status(500).json({ error: '获取弹幕失败' });
  }
});

// 添加弹幕上传接口
app.post('/api/danmaku/send', async (req, res) => {
  try {
    const { content, color } = req.body;
    
    if (!content) {
      return res.status(400).json({ error: '弹幕内容不能为空' });
    }
    
    // 创建新弹幕并保存到数据库
    const danmaku = await Danmaku.create({
      content,
      color: color || '#ffffff'
    });
    
    // 通过WebSocket广播新弹幕
    io.emit('danmaku', danmaku);
    
    res.json({ message: '发送成功', danmaku });
  } catch (error) {
    console.error('发送弹幕失败:', error);
    res.status(500).json({ error: '发送弹幕失败' });
  }
});

// 添加背景图片上传接口
app.post('/api/background/upload', imageUpload.single('image'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: '请选择图片文件' });
    }
    
    const imageUrl = `/static/images/${req.file.filename}`;
    res.json({ 
      message: '上传成功',
      url: imageUrl
    });
  } catch (error) {
    console.error('上传背景图片失败:', error);
    res.status(500).json({ error: '上传背景图片失败: ' + error.message });
  }
});

// 获取当前背景图片
app.get('/api/background', (req, res) => {
  try {
    const backgroundPath = path.join(__dirname, '../static/images/background.jpg');
    if (fs.existsSync(backgroundPath)) {
      res.json({ url: '/static/images/background.jpg' });
    } else {
      res.json({ url: null });
    }
  } catch (error) {
    console.error('获取背景图片失败:', error);
    res.status(500).json({ error: '获取背景图片失败' });
  }
});

// 添加奖品图片上传接口
app.post('/api/prize/upload', prizeImageUpload.single('image'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: '请选择图片文件' });
    }
    
    const imageUrl = `/static/prizes/${req.file.filename}`;
    res.json({ 
      message: '上传成功',
      url: imageUrl
    });
  } catch (error) {
    console.error('上传奖品图片失败:', error);
    res.status(500).json({ error: '上传奖品图片失败: ' + error.message });
  }
});

// 添加通配符路由，处理前端路由
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../../frontend/dist/index.html'));
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, '0.0.0.0', () => {
  console.log(`服务器运行在端口 ${PORT}`);
}); 